<template>
    <!-- pages/phone/index.wxml -->
    <view class="phone">
        <view class="title">
            <view>您好，</view>
            <view>欢迎来到邻里停</view>
        </view>
        <view class="gologin">
            <van-field v-model="value" label="+86" placeholder="请输入手机号" />
            <view class="yzm">
                <van-field v-model="sms" center clearable placeholder="请输入短信验证码">
                    <van-button slot="button" @tap.native="handleClick" :disabled="show">
                        <view v-if="show" class="time">
                            {{ timer }}
                            <span>s</span>
                        </view>
                        <view v-else class="text">获取验证码</view>
                    </van-button>
                </van-field>
            </view>
        </view>
        <view class="loading">
            <van-loading type="spinner" color="#1989fa" v-if="loading" text-size="40rpx" />
        </view>
        <view class="login-btn">
            <van-button type="info" @tap.native="goLogin">登录/注册</van-button>
        </view>
    </view>
</template>

<script>
import util from './../../utils/util.js';
import api from './../../utils/api.js';
export default {
    data() {
        return {
            value: '',
            //手机号
            sms: '',
            //验证码
            show: false,
            timer: '',
            center: 'false',
            //从登陆页跳转还是个人中心页面跳转
            loading: false,
            weixinCode: ''
        };
    },
    onLoad: function (options) {
        let that = this;
        uni.login({
            success(res) {
                that.setData({
                    weixinCode: res.code
                });
            }
        });
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {},
    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        this.getWeixincode();
    },
    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {},
    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {},
    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {},
    /**
     * 页面上拉触底事件的处理函数
     */
    // onShareAppMessage: function() {}
    onReachBottom: function () {},
    /**
     * 用户点击右上角分享
     */ methods: {
        /**
         * 生命周期函数--监听页面加载
         */
        handleClick() {
            if (this.show) {
                return;
            }

            let regs = /^((13[0-9])|(17[0-9])|(15[0-9])|(16[0-9])|(18[0-9])|(19[0-9]))\d{8}$/;

            if (regs.test(this.value)) {
                this.getsendVerificationCode();
                var time = 60;
                var times = null;
                const that = this;
                times = setInterval(function () {
                    // 定时器到底了 兄弟们回家啦
                    if (time == 1) {
                        clearInterval(times);
                        that.setData({
                            show: false
                        });
                    } else {
                        time--;
                        that.setData({
                            timer: time,
                            show: true
                        });
                    }
                }, 1000);
            } else {
                uni.showToast({
                    title: '请输入正确格式',
                    icon: 'none'
                });
            }
        },

        //登陆
        getparkLogin() {
            this.setData({
                loading: true
            });
            const param = {
                loginName: this.value,
                verificationType: 4,
                verificationCode: this.sms
            };
            uni.setStorage({
                key: 'phoneNumber',
                data: this.value
            }); //手机号

            uni.setStorage({
                key: 'sms',
                data: this.sms
            }); //手机号

            util.request(
                api.parkLogin +
                    '?loginName=' +
                    this.value +
                    '&verificationCode=' +
                    this.sms +
                    '&verificationType=4' +
                    '&code=' +
                    this.weixinCode +
                    '&activityCode=' +
                    uni.getStorageSync('activityCode') ||
                    '' + '&shareId=' + uni.getStorageSync('shareId') ||
                    '',
                '',
                'POST' // "application/x-www-form-urlencoded"
            ).then((res) => {
                if (res.code == 0) {
                    this.setData({
                        loading: false
                    });
                    uni.setStorage({
                        key: 'openId',
                        data: res.data.busiInfo.openId
                    }); //openId

                    uni.setStorage({
                        key: 'status',
                        data: true
                    }); //状态

                    uni.setStorage({
                        key: 'phoneNumber',
                        data: res.data.busiInfo.phoneNumber
                    }); //手机号

                    uni.setStorage({
                        key: 'name',
                        data: res.data.busiInfo.name
                    }); //姓名

                    uni.setStorage({
                        key: 'plateNos',
                        data: (res.data.busiInfo.plateNos && res.data.busiInfo.plateNos.map((e) => e).toString()) || ''
                    }); //用户车牌号

                    uni.setStorage({
                        key: 'faceImageUrl',
                        data: res.data.busiInfo.faceImageUrl
                    }); //头像

                    uni.setStorage({
                        key: 'AUTHORIZATION',
                        data: res.data.busiInfo.token
                    }); //token

                    uni.setStorage({
                        key: 'identityId',
                        data: res.data.busiInfo.identityId
                    }); //用户id

                    uni.setStorage({
                        key: 'unionId',
                        data: res.data.busiInfo.unionId
                    }); //用户id

                    if (res.data.busiInfo.plateNos != null && res.data.busiInfo.plateNos.length > 0) {
                        // v2.5.4新加的访客链接进入时的逻辑
                        if (uni.getStorageSync('visitor_code')) {
                            uni.redirectTo({
                                url: '../newBookpark/newBookpark?param=' + uni.getStorageSync('visitor_parkcode')
                            });
                        } else {
                            uni.switchTab({
                                url: '../home/index'
                            });
                        }
                    } else {
                        // v2.5.4新加的访客链接进入时的逻辑
                        if (uni.getStorageSync('visitor_code')) {
                            uni.redirectTo({
                                url: '../addLicense/addLicense'
                            });
                        } else {
                            uni.switchTab({
                                url: '../home/index'
                            });
                        }
                    }
                } else if (res.busiCode === '00001') {
                    this.setData({
                        loading: false
                    });
                    this.setparkRegister(); //直接注册
                } else if (res.busiCode === '04001') {
                    this.setData({
                        loading: false
                    });
                    uni.showToast({
                        title: res.msg,
                        icon: 'none'
                    });
                    this.getWeixincode();
                } else {
                    this.setData({
                        loading: false
                    });
                    uni.showToast({
                        title: res.msg,
                        icon: 'none'
                    });
                    this.getWeixincode();
                }
            });
        },

        goLogin() {
            // let regs = /^((13[0-9])|(17[0-9])|(15[0-9])|(16[0-9])|(18[0-9])|(19[0-9]))\d{8}$/;
            if (this.value == '') {
                uni.showToast({
                    title: '请输入手机号',
                    icon: 'none'
                });
            } else if (this.sms == '') {
                uni.showToast({
                    title: '请输入验证码',
                    icon: 'none'
                });
            } else {
                this.getparkLogin();
            }
        },

        //获取验证码
        getsendVerificationCode() {
            const param = {
                phoneNumber: this.value,
                verificationType: 4
            };
            util.request(api.sendVerificationCode, param, 'POST').then((res) => {
                if (res.success) {
                    // return res.data;
                    console.log(res);
                }
            });
        },

        getWeixincode() {
            let that = this;
            uni.login({
                success(res) {
                    console.log(res);
                    that.setData({
                        weixinCode: res.code
                    });
                }
            });
        },

        // 在该页面-若用户没有注册，则自动给注册掉！
        setparkRegister() {
            const param = {
                loginName: uni.getStorageSync('phoneNumber'),
                name: '用户_' + util.randomWord(false, 10),
                plates: []
            }; // 如果从分享进来注册的，还需要加上分享人的参数

            if (uni.getStorageSync('shareId')) {
                param.originUnionId = uni.getStorageSync('shareId');
            }

            if (uni.getStorageSync('activityCode')) {
                param.activityCode = uni.getStorageSync('activityCode') || '';
            }

            util.request(api.parkRegister, param, 'POST')
                .then((res) => {
                    if (res.code == 0) {
                        this.getparkLogin();
                        uni.removeStorageSync('shareId');
                    } else {
                        uni.showToast({
                            title: res.msg,
                            icon: 'none'
                        });
                    }
                })
                .catch((err) => {
                    uni.showToast({
                        title: err,
                        icon: 'none'
                    });
                });
        }
    }
};
</script>
<style>
@import './index.css';
</style>
